package com.worklog.controller;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.worklog.model.User;
import com.worklog.util.ToolUtil;

@Controller
public class HomeController {
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String login() {
		return "login";
	}

	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String login(HttpServletRequest request, User user, Model model) {
		if (StringUtils.isEmpty(user.getUsername()) || StringUtils.isEmpty(user.getPassword())) {
			request.setAttribute("msg", "用户名或密码不能为空！");
			return "login";
		}
		// 获取HttpSession中的验证码
		String verifyCode = (String) request.getSession().getAttribute("verifyCode");
		// 获取用户请求表单中输入的验证码
		String submitCode = WebUtils.getCleanParam(request, "verify");
		if (StringUtils.isEmpty(submitCode) || !verifyCode.toLowerCase().equals(submitCode.toLowerCase())) {
			request.setAttribute("msg", "验证码不正确");
			return "login";
		}

		Subject subject = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword(),
				ToolUtil.getIpAddr(request));
		try {
			subject.login(token);
			return "redirect:manager";
		} catch (UnknownAccountException uae) {
			request.setAttribute("msg", "未知账户");
			return "login";
		} catch (IncorrectCredentialsException ice) {
			request.setAttribute("msg", "密码不正确");
			return "login";
		} catch (LockedAccountException lae) {
			token.clear();
			request.setAttribute("msg", "用户已经被锁定不能登录，请与管理员联系！");
			return "login";
		} catch (ExcessiveAttemptsException eae) {
			token.clear();
			request.setAttribute("msg", "用户名或密码错误次数过多");
			return "login";
		} catch (AuthenticationException e) {
			token.clear();
			request.setAttribute("msg", "用户或密码不正确！");
			return "login";
		}
	}

	@RequestMapping(value = { "/manager", "" })
	public String usersPage() {
		return "manager/manager";
	}

	@RequestMapping("/rolesPage")
	public String rolesPage() {
		return "role/roles";
	}

	@RequestMapping("/resourcesPage")
	public String resourcesPage() {
		return "resources/resources";
	}

	@RequestMapping("/403")
	public String forbidden() {
		return "403";
	}
}
